﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web.Services;
using System.Xml.Linq;
using Eagleshoes.ERPService.Properties;

namespace Eagleshoes.ERPService
{
	/// <summary>
	/// Service1 的摘要说明
	/// </summary>
	[WebService(Namespace = "http://www.eagleshoes.biz/")]
	[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
	[ToolboxItem(false)]
	// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。
		// [System.Web.Script.Services.ScriptService]
	public class CartonService : WebService
	{
		#region 库存查询

		/// <summary>
		/// 货品库存查询
		/// </summary>
		/// <param name="barcode"></param>
		/// <returns></returns>
		[WebMethod(Description = "按货品条码进行库存查询")]
		public GoodsInventory GetGoodsInventoryByBarcode(string barcode)
		{
			GoodsInventory gi = null;
			var conn = new SqlConnection(Settings.Default.e3db);
			SqlCommand cmd = conn.CreateCommand();
			cmd.CommandText = "SELECT code,name,quantity,realqty,unitname,barcode FROM view_goods where barcode=@barcode";
			cmd.Parameters.Add(new SqlParameter("@barcode", SqlDbType.VarChar));
			cmd.Parameters["@barcode"].Value = barcode;
			try
			{
				conn.Open();
				SqlDataReader dr = cmd.ExecuteReader();
				if (dr.Read())
				{
					gi = new GoodsInventory
						{
							GoodsCode = dr.GetString(0),
							GoodsName = dr.GetString(1),
							Quantities = dr.GetDecimal(2),
							StockQuantities = dr.GetDecimal(3),
							Unit = dr.GetString(4),
							GoodsBarcode = dr.GetString(5)
						};
				}
				dr.Close();
			}
			finally
			{
				if (conn.State != ConnectionState.Closed)
				{
					conn.Close();
				}
			}
			return gi;
		}

		#endregion

		/// <summary>
		/// 保存出货扫描资料
		/// </summary>
		/// <param name="cartonCodes"></param>
		/// <returns></returns>
		[WebMethod(Description = "保存出货扫描资料")]
		public bool SaveShippingScanedData(List<string> cartonCodes)
		{
			using (var conn = new SqlConnection(Settings.Default.e3db))
			{
				SqlCommand cmd = conn.CreateCommand();
				cmd.CommandText = "insert into mnf_BarRecord (btype,Cartons) values (3,@Cartons)";
				cmd.Parameters.Add("@Cartons", SqlDbType.VarChar);
				conn.Open();
				SqlTransaction tran = conn.BeginTransaction();
				try
				{
					cmd.Transaction = tran;
					foreach (var barcode in cartonCodes)
					{
						cmd.Parameters["@Cartons"].Value = barcode;
						cmd.ExecuteNonQuery();
					}
					tran.Commit();
					return true;
				}
				catch
				{
					tran.Rollback();
					return false;
				}
				finally
				{
					if (conn.State != ConnectionState.Closed)
					{
						conn.Close();
					}
				}
			}
		}

		#region 装箱扫描

		[WebMethod(Description = "在线获取指定外箱条码，适用于在线包装扫描")]
		public PackagingCarton GetPackagingCartonOnline(string barcode)
		{
			PackagingCarton pc = null;
			var conn = new SqlConnection(Settings.Default.e3db);
			var cmd = conn.CreateCommand();
            cmd.CommandText = @"SELECT TOP(1) BoxBarCode,isnull(SOrderCode,'<null>') as SOrderCode,PackCode FROM View_PackBarCode WHERE BoxBarCode=@code";
			cmd.Parameters.Add(new SqlParameter("@code", SqlDbType.VarChar));
            try
            {
				conn.Open();
				cmd.Parameters["@code"].Value = barcode;
				var dr = cmd.ExecuteReader();
				if (dr.Read())
				{
					pc = new PackagingCarton { CartonBarcode = dr.GetString(0), SalesOrderCode = dr.GetString(1), PackagingOrderCode = dr.GetString(2) };
					dr.Close();

					cmd.CommandText = @"select BoxBarCode,Goodsbarcode,quantity,goodscode,specs from View_PackBarCode where BoxBarCode=@code";
					dr = cmd.ExecuteReader();
					while (dr.Read())
					{
						pc.Boxes.Add(new PackagingBox
							{
								BoxBarcode = dr.GetString(1),
								CartonBarcode = dr.GetString(0),
								GoodsCode = dr.GetString(3),
								Quantities = Convert.ToInt32(dr.GetDecimal(2)),
								Spec = dr.GetString(4)
							});
					}
					dr.Close();
				}
				else
				{
					dr.Close();
                }
            }
            catch
            {
                return null;
            }
            finally
            {
                if (conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                }
            }
			return pc;
		}

		/// <summary>
		/// 从预置的数据表中加载包装单资料
		/// </summary>
		/// <returns></returns>
		[WebMethod(Description = "在线从预置的数据表中加载包装单资料")]
		public List<PackagingCarton> GetCartonListFromBoxBarDownTable()
		{
			var pcList = new List<PackagingCarton>();

			var conn = new SqlConnection(Settings.Default.e3db);

			//try
			//{
				conn.Open();
				SqlCommand cmd = conn.CreateCommand();
				cmd.CommandText = "SELECT DISTINCT BoxBarCode,SOrderCode,PackCode FROM mnf_BoxBarDown";
				//cmd.CommandText = "SELECT DISTINCT BoxBarCode,SOrderCode,PackCode FROM View_PackBarCode WHERE SOrderCode='SO-2013-07-00221'";

				var dr = cmd.ExecuteReader();
				while (dr.Read())
				{
					pcList.Add(new PackagingCarton {CartonBarcode = dr.GetString(0), SalesOrderCode = dr.GetString(1), PackagingOrderCode = dr.GetString(2)});
				}
				dr.Close();

				cmd.CommandText = @"SELECT BoxBarCode,Goodsbarcode,quantity,goodscode,specs FROM mnf_BoxBarDown";
				//cmd.CommandText = @"SELECT BoxBarCode,Goodsbarcode,quantity,goodscode,specs FROM View_PackBarCode WHERE SOrderCode='SO-2013-07-00221'";
				dr = cmd.ExecuteReader();
				while (dr.Read())
				{
					var box = new PackagingBox
						{
							BoxBarcode = dr.GetString(1),
							CartonBarcode = dr.GetString(0),
							GoodsCode = dr.GetString(3),
							Quantities = Convert.ToInt32(dr.GetDecimal(2)),
							Spec = dr.GetString(4)
						};
					var pc = (from c in pcList
					          where c.CartonBarcode == box.CartonBarcode
					          select c).SingleOrDefault();
					if (pc != null)
					{
						pc.Boxes.Add(box);
					}
				}
				dr.Close();
			//}
			//finally
			//{
				if (conn.State != ConnectionState.Closed)
				{
					conn.Close();
				}
			//}
			return pcList;
		}

		/// <summary>
		/// 保存包装扫描资料
		/// </summary>
		/// <returns></returns>
		[WebMethod(Description = "保存已扫描打包的包装箱资料")]
		public bool SavePackaginScanedData(List<PackagingScaned> scanedData)
		{
			using (var conn = new SqlConnection(Settings.Default.e3db))
			{
				SqlCommand cmd = conn.CreateCommand();
				cmd.CommandText = "insert into mnf_BoxBarRecord (bigCode,smallCode,quantity,addate) values (@bigCode,@smallCode,@quantity,@addate)";
				cmd.Parameters.Add("@bigCode", SqlDbType.VarChar);
				cmd.Parameters.Add("@smallCode", SqlDbType.VarChar);
				cmd.Parameters.Add("@quantity", SqlDbType.Decimal);
				cmd.Parameters.Add("@addate", SqlDbType.DateTime);
				conn.Open();
				var tr = conn.BeginTransaction();
				cmd.Transaction = tr;
				try
				{
					foreach (var data in scanedData)
					{
						cmd.Parameters["@bigCode"].Value = data.CartonBarcode;
						cmd.Parameters["@Addate"].Value = data.ScanedDate;
						cmd.Parameters["@smallCode"].Value = data.BoxBarcode;
						cmd.Parameters["@quantity"].Value = Convert.ToDecimal(data.Quantities);
						cmd.ExecuteNonQuery();
					}
					tr.Commit();
					return true;
				}
				catch
				{
					tr.Rollback();
					return false;
				}
				finally
				{
					if (conn.State != ConnectionState.Closed)
					{
						conn.Close();
					}
				}
			}
		}

		#endregion
	}
}